<template>
  <div class="operatingRevenue">
    <x-header class="header" :left-options="{showBack: showHeaderBack,preventGoBack:true}" @on-click-back="goToPage" ref="header">总营业收入</x-header>
    <div class="topHolder"></div>
    <card class="gridDisplay">
      <div class="card-padding" slot="content" style="padding-top: 0;">
        <div class="filterArea dateFilter" ref="filterArea">
          <group-title style="text-align: center;">当前显示日期：{{choosenDate}}<br/></group-title>
          <x-button :show-loading="loadingStatus" :disabled="loadingStatus" @click.native="changeDate(1)" class="inlineBtn">今日</x-button>
          <x-button :show-loading="loadingStatus" :disabled="loadingStatus" @click.native="changeDate(2)" class="inlineBtn">昨日</x-button>
          <a v-if="loadingStatus" class="datePicker"><i class="iconfont icon-rilicalendar107"></i></a>
          <datetime v-else v-model="choosenDate" :start-date="startDate" :end-date="endDate" @on-confirm="changeDate(0)" class="datePicker">
            <i class="iconfont icon-rilicalendar107"></i>
          </datetime>
        </div>
        <h2 class="title">
          <span v-text="'¥ ' + formatCurrency(revenueInfo.total)">0</span>元<br/>
          <small>总营业收入</small>
        </h2>
      </div>
    </card>
    <group title="营业收入明细：">
      <canvas height="260" class="noselect" ref="vChart"></canvas>
      <div style="height: 30px;"></div>
    </group>
  </div>
</template>

<script>
  import F2 from '@antv/f2/build/f2-all.js'
  import {XButton, Card, Group, Datetime, GroupTitle, dateFormat ,numberComma } from 'vux'
  import {getOperatingRevenue} from "../../api";
  import {message,toDecimal2} from "../../common/util";

  export default {
    name:'operatingRevenue',
    data(){
      return{
        showHeaderBack:this.GLOBAL.showHeaderBack,
        loadingStatus:true,
        choosenDate:dateFormat(new Date(), 'YYYY-MM-DD'),
        startDate:'2019-01-01',
        endDate:dateFormat(new Date(), 'YYYY-MM-DD'),
        revenueInfo:{},
        chartHeight:250,
        chartData:[],
        chart:{}
      }
    },
    components:{
      XButton,
      Card,
      Group,
      Datetime,
      GroupTitle
    },
    computed:{
    },
    methods:{
      goToPage(){
        this.$router.push({path:'/'})
      },
      formatCurrency(number){
        return numberComma(toDecimal2(number))
      },
      changeDate(value){
        console.log(value)
        switch (value) {
          case 1:this.choosenDate = dateFormat(new Date(), 'YYYY-MM-DD');break;
          case 2:this.choosenDate = dateFormat(new Date().setDate(new Date().getDate()-1), 'YYYY-MM-DD');break;
          default: break;
        }
        console.log(this.choosenDate)
        this.changeChartData()
      },
      refreshPage(params){
        this.loadingStatus = true
        this.chartHeight = 250
        this.chartData = []
        getOperatingRevenue(this.choosenDate).then((res)=>{
          if(res.status == 'success'){
            this.revenueInfo = res.data
            this.chartHeight += this.revenueInfo.detail.length * 20
            this.revenueInfo.detail.forEach(item =>{
              this.chartData.push({amount: item.value,ratio: item.value/this.revenueInfo.total,memo: item.name,const: 'const'})
            })
          }else if(res.status == 'error') {
            message({message:res.msg,type:'error'})
            console.log('getOperatingRevenue error info:', res.msg)
          }
          if(params && params.callback && typeof params.callback == 'function')params.callback(res.status)
        }).catch((err)=>{console.log('getOperatingRevenue catch info:',err)})
      },
      initChart(){
        const windowWidth = window.innerWidth
        const windowHeight = window.innerHeight
        this.chart = new F2.Chart({
          id: this.$refs.vChart,
          width: windowWidth,
          height: this.chartHeight ? this.chartHeight : (windowWidth > windowHeight ? (windowHeight - 54) : windowWidth * 0.707),
          pixelRatio: window.devicePixelRatio
        });
        this.chart.source(this.chartData)
        this.chart.coord('polar', {
          transposed: true,
          innerRadius: 0.4,
          radius: 0.75
        });
        this.chart.axis(false);
        this.chart.legend({
          position: 'bottom',
          align: 'center',
          itemMarginBottom: 20
        });
        this.chart.tooltip(false);
        this.chart.guide().html({
          position: ['50%', '50%'],
          html: '<div style="width: 80px;height: 20px;text-align: center;line-height: 20px;font-size: 0.9rem" id="textContent">收入明细</div>'
        });
        // 配置文本饼图
        this.chart.pieLabel({
          sidePadding: 15,
          label1: function label1(data) {
            return {
              text: data.memo,
              fill: '#808080'
            };
          },
          label2: function label2(data) {
            return {
              fill: '#000000',
              text: '¥' + data.amount + '元'
            };
          }
        });
        this.chart.interval().position('const*ratio').color('memo', ['#1890FF', '#13C2C2', '#2FC25B', '#FACC14', '#F04864', '#8543E0', '#3436C7', '#223273']).adjust('stack');
        this.chart.render();
        // 绘制内阴影
        var frontPlot = this.chart.get('frontPlot');
        var coord = this.chart.get('coord'); // 获取坐标系对象
        frontPlot.addShape('sector', {
          attrs: {
            x: coord.center.x,
            y: coord.center.y,
            r: coord.circleRadius * coord.innerRadius * 1.2, // 全半径
            r0: coord.circleRadius * coord.innerRadius,
            fill: '#000',
            opacity: 0.15
          }
        });
        this.chart.get('canvas').draw();
      },
      changeChartData(){
        this.refreshPage({callback:(status)=>{
            if(status == 'success') this.chart.changeData(this.chartData)
            this.loadingStatus = false
          }})
      },
      reInitChart(){
        this.chart.destroy()
        this.initChart()
      }
    },
    mounted(){
      this.refreshPage({callback:(status)=>{
          if(status == 'success'){
            this.initChart()
            window.addEventListener('resize', this.reInitChart)
          }
          this.loadingStatus = false
          this.$store.commit('updateLoadingStatus',{isLoading:false})
        }})
    },
    beforeDestroy () {
      window.removeEventListener('resize', this.reInitChart)
      this.chart.destroy()
    }
  }
</script>

<style lang="scss">
  .operatingRevenue{
    .gridDisplay{
      .filterArea{
        &.dateFilter{
          margin-bottom: 0.5rem;
          .datePicker{
            float: right;padding: 0;
            &.weui-cell:before{border-top: none;}
            i{font-size: 2rem;color:#535353;}
          }
        }
        .filterItem{margin-top: 0.5rem;}
      }
      h2.title{
        line-height: 1.8rem;color: #636363;font-size:2rem;text-align: center;margin: 1rem 0;
        small{font-size:1rem;color: #999999;}
      }
      .data{display: inline-block;height:1.5rem;}
    }
    .noselect {
      -webkit-touch-callout: none; /* iOS Safari */
      -webkit-user-select: none; /* Safari */
      -khtml-user-select: none; /* Konqueror HTML */
      -moz-user-select: none; /* Firefox */
      -ms-user-select: none; /* Internet Explorer/Edge */
      user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome and Opera */
    }
  }
</style>
